* (bug 3786) Experimental support for MySQL 4.1/5.0 utf8 charset mode
[lhc/web/wiklou.git] / includes / Database.php
1 <?php
2 /**
3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
5 * @package MediaWiki
6 */
7
8 /**
9 * Depends on the CacheManager
10 */
11 require_once( 'CacheManager.php' );
12
13 /** See Database::makeList() */
14 define( 'LIST_COMMA', 0 );
15 define( 'LIST_AND', 1 );
16 define( 'LIST_SET', 2 );
17 define( 'LIST_NAMES', 3);
18 define( 'LIST_OR', 4);
19
20 /** Number of times to re-try an operation in case of deadlock */
21 define( 'DEADLOCK_TRIES', 4 );
22 /** Minimum time to wait before retry, in microseconds */
23 define( 'DEADLOCK_DELAY_MIN', 500000 );
24 /** Maximum time to wait before retry */
25 define( 'DEADLOCK_DELAY_MAX', 1500000 );
26
27 class DBObject {
28 var $mData;
29
30 function DBObject($data) {
31 $this->mData = $data;
32 }
33
34 function isLOB() {
35 return false;
36 }
37
38 function data() {
39 return $this->mData;
40 }
41 };
42
43 /**
44 * Database abstraction object
45 * @package MediaWiki
46 */
47 class Database {
48
49 #------------------------------------------------------------------------------
50 # Variables
51 #------------------------------------------------------------------------------
52 /**#@+
53 * @access private
54 */
55 var $mLastQuery = '';
56
57 var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
58 var $mOut, $mOpened = false;
59
60 var $mFailFunction;
61 var $mTablePrefix;
62 var $mFlags;
63 var $mTrxLevel = 0;
64 var $mErrorCount = 0;
65 /**#@-*/
66
67 #------------------------------------------------------------------------------
68 # Accessors
69 #------------------------------------------------------------------------------
70 # These optionally set a variable and return the previous state
71
72 /**
73 * Fail function, takes a Database as a parameter
74 * Set to false for default, 1 for ignore errors
75 */
76 function failFunction( $function = NULL ) {
77 return wfSetVar( $this->mFailFunction, $function );
78 }
79
80 /**
81 * Output page, used for reporting errors
82 * FALSE means discard output
83 */
84 function &setOutputPage( &$out ) {
85 $this->mOut =& $out;
86 }
87
88 /**
89 * Boolean, controls output of large amounts of debug information
90 */
91 function debug( $debug = NULL ) {
92 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
93 }
94
95 /**
96 * Turns buffering of SQL result sets on (true) or off (false).
97 * Default is "on" and it should not be changed without good reasons.
98 */
99 function bufferResults( $buffer = NULL ) {
100 if ( is_null( $buffer ) ) {
101 return !(bool)( $this->mFlags & DBO_NOBUFFER );
102 } else {
103 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
104 }
105 }
106
107 /**
108 * Turns on (false) or off (true) the automatic generation and sending
109 * of a "we're sorry, but there has been a database error" page on
110 * database errors. Default is on (false). When turned off, the
111 * code should use wfLastErrno() and wfLastError() to handle the
112 * situation as appropriate.
113 */
114 function ignoreErrors( $ignoreErrors = NULL ) {
115 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
116 }
117
118 /**
119 * The current depth of nested transactions
120 * @param integer $level
121 */
122 function trxLevel( $level = NULL ) {
123 return wfSetVar( $this->mTrxLevel, $level );
124 }
125
126 /**
127 * Number of errors logged, only useful when errors are ignored
128 */
129 function errorCount( $count = NULL ) {
130 return wfSetVar( $this->mErrorCount, $count );
131 }
132
133 /**#@+
134 * Get function
135 */
136 function lastQuery() { return $this->mLastQuery; }
137 function isOpen() { return $this->mOpened; }
138 /**#@-*/
139
140 function setFlag( $flag ) {
141 $this->mFlags |= $flag;
142 }
143
144 function clearFlag( $flag ) {
145 $this->mFlags &= ~$flag;
146 }
147
148 function getFlag( $flag ) {
149 return !!($this->mFlags & $flag);
150 }
151
152 #------------------------------------------------------------------------------
153 # Other functions
154 #------------------------------------------------------------------------------
155
156 /**#@+
157 * @param string $server database server host
158 * @param string $user database user name
159 * @param string $password database user password
160 * @param string $dbname database name
161 */
162
163 /**
164 * @param failFunction
165 * @param $flags
166 * @param string $tablePrefix Database table prefixes. By default use the prefix gave in LocalSettings.php
167 */
168 function Database( $server = false, $user = false, $password = false, $dbName = false,
169 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
170
171 global $wgOut, $wgDBprefix, $wgCommandLineMode;
172 # Can't get a reference if it hasn't been set yet
173 if ( !isset( $wgOut ) ) {
174 $wgOut = NULL;
175 }
176 $this->mOut =& $wgOut;
177
178 $this->mFailFunction = $failFunction;
179 $this->mFlags = $flags;
180
181 if ( $this->mFlags & DBO_DEFAULT ) {
182 if ( $wgCommandLineMode ) {
183 $this->mFlags &= ~DBO_TRX;
184 } else {
185 $this->mFlags |= DBO_TRX;
186 }
187 }
188
189 /*
190 // Faster read-only access
191 if ( wfReadOnly() ) {
192 $this->mFlags |= DBO_PERSISTENT;
193 $this->mFlags &= ~DBO_TRX;
194 }*/
195
196 /** Get the default table prefix*/
197 if ( $tablePrefix == 'get from global' ) {
198 $this->mTablePrefix = $wgDBprefix;
199 } else {
200 $this->mTablePrefix = $tablePrefix;
201 }
202
203 if ( $server ) {
204 $this->open( $server, $user, $password, $dbName );
205 }
206 }
207
208 /**
209 * @static
210 * @param failFunction
211 * @param $flags
212 */
213 function newFromParams( $server, $user, $password, $dbName,
214 $failFunction = false, $flags = 0 )
215 {
216 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
217 }
218
219 /**
220 * Usually aborts on failure
221 * If the failFunction is set to a non-zero integer, returns success
222 */
223 function open( $server, $user, $password, $dbName ) {
224 # Test for missing mysql.so
225 # First try to load it
226 if (!@extension_loaded('mysql')) {
227 @dl('mysql.so');
228 }
229
230 # Otherwise we get a suppressed fatal error, which is very hard to track down
231 if ( !function_exists( 'mysql_connect' ) ) {
232 die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
233 }
234
235 $this->close();
236 $this->mServer = $server;
237 $this->mUser = $user;
238 $this->mPassword = $password;
239 $this->mDBname = $dbName;
240
241 $success = false;
242
243 if ( $this->mFlags & DBO_PERSISTENT ) {
244 @/**/$this->mConn = mysql_pconnect( $server, $user, $password );
245 } else {
246 # Create a new connection...
247 if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
248 @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
249 } else {
250 # On PHP 4.1 the new_link parameter is not available. We cannot
251 # guarantee that we'll actually get a new connection, and this
252 # may cause some operations to fail possibly.
253 @/**/$this->mConn = mysql_connect( $server, $user, $password );
254 }
255 }
256
257 if ( $dbName != '' ) {
258 if ( $this->mConn !== false ) {
259 $success = @/**/mysql_select_db( $dbName, $this->mConn );
260 if ( !$success ) {
261 wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
262 }
263 } else {
264 wfDebug( "DB connection error\n" );
265 wfDebug( "Server: $server, User: $user, Password: " .
266 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
267 $success = false;
268 }
269 } else {
270 # Delay USE query
271 $success = (bool)$this->mConn;
272 }
273
274 if ( !$success ) {
275 $this->reportConnectionError();
276 }
277
278 global $wgDBmysql5;
279 if( $wgDBmysql5 ) {
280 // Tell the server we're communicating with it in UTF-8.
281 // This may engage various charset conversions.
282 $this->query( 'SET NAMES utf8' );
283 }
284
285 $this->mOpened = $success;
286 return $success;
287 }
288 /**#@-*/
289
290 /**
291 * Closes a database connection.
292 * if it is open : commits any open transactions
293 *
294 * @return bool operation success. true if already closed.
295 */
296 function close()
297 {
298 $this->mOpened = false;
299 if ( $this->mConn ) {
300 if ( $this->trxLevel() ) {
301 $this->immediateCommit();
302 }
303 return mysql_close( $this->mConn );
304 } else {
305 return true;
306 }
307 }
308
309 /**
310 * @access private
311 * @param string $msg error message ?
312 */
313 function reportConnectionError() {
314 if ( $this->mFailFunction ) {
315 if ( !is_int( $this->mFailFunction ) ) {
316 $ff = $this->mFailFunction;
317 $ff( $this, $this->lastError() );
318 }
319 } else {
320 wfEmergencyAbort( $this, $this->lastError() );
321 }
322 }
323
324 /**
325 * Usually aborts on failure
326 * If errors are explicitly ignored, returns success
327 */
328 function query( $sql, $fname = '', $tempIgnore = false ) {
329 global $wgProfiling, $wgCommandLineMode;
330
331 if ( wfReadOnly() ) {
332 # This is a quick check for the most common kinds of write query used
333 # in MediaWiki, to provide extra safety in addition to UI-level checks.
334 # It is not intended to prevent every conceivable write query, or even
335 # to handle such queries gracefully.
336 if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
337 wfDebug( "Write query from $fname blocked\n" );
338 return false;
339 }
340 }
341
342 if ( $wgProfiling ) {
343 # generalizeSQL will probably cut down the query to reasonable
344 # logging size most of the time. The substr is really just a sanity check.
345
346 # Who's been wasting my precious column space? -- TS
347 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
348 $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
349
350 wfProfileIn( 'Database::query' );
351 wfProfileIn( $profName );
352 }
353
354 $this->mLastQuery = $sql;
355
356 # Add a comment for easy SHOW PROCESSLIST interpretation
357 if ( $fname ) {
358 $commentedSql = "/* $fname */ $sql";
359 } else {
360 $commentedSql = $sql;
361 }
362
363 # If DBO_TRX is set, start a transaction
364 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() && $sql != 'BEGIN' ) {
365 $this->begin();
366 }
367
368 if ( $this->debug() ) {
369 $sqlx = substr( $commentedSql, 0, 500 );
370 $sqlx = strtr( $sqlx, "\t\n", ' ' );
371 wfDebug( "SQL: $sqlx\n" );
372 }
373
374 # Do the query and handle errors
375 $ret = $this->doQuery( $commentedSql );
376
377 # Try reconnecting if the connection was lost
378 if ( false === $ret && ( $this->lastErrno() == 2013 || $this->lastErrno() == 2006 ) ) {
379 # Transaction is gone, like it or not
380 $this->mTrxLevel = 0;
381 wfDebug( "Connection lost, reconnecting...\n" );
382 if ( $this->ping() ) {
383 wfDebug( "Reconnected\n" );
384 $ret = $this->doQuery( $commentedSql );
385 } else {
386 wfDebug( "Failed\n" );
387 }
388 }
389
390 if ( false === $ret ) {
391 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
392 }
393
394 if ( $wgProfiling ) {
395 wfProfileOut( $profName );
396 wfProfileOut( 'Database::query' );
397 }
398 return $ret;
399 }
400
401 /**
402 * The DBMS-dependent part of query()
403 * @param string $sql SQL query.
404 */
405 function doQuery( $sql ) {
406 if( $this->bufferResults() ) {
407 $ret = mysql_query( $sql, $this->mConn );
408 } else {
409 $ret = mysql_unbuffered_query( $sql, $this->mConn );
410 }
411 return $ret;
412 }
413
414 /**
415 * @param $error
416 * @param $errno
417 * @param $sql
418 * @param string $fname
419 * @param bool $tempIgnore
420 */
421 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
422 global $wgCommandLineMode, $wgFullyInitialised;
423 # Ignore errors during error handling to avoid infinite recursion
424 $ignore = $this->ignoreErrors( true );
425 ++$this->mErrorCount;
426
427 if( $ignore || $tempIgnore ) {
428 wfDebug("SQL ERROR (ignored): $error\n");
429 } else {
430 $sql1line = str_replace( "\n", "\\n", $sql );
431 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
432 wfDebug("SQL ERROR: " . $error . "\n");
433 if ( $wgCommandLineMode || !$this->mOut || empty( $wgFullyInitialised ) ) {
434 $message = "A database error has occurred\n" .
435 "Query: $sql\n" .
436 "Function: $fname\n" .
437 "Error: $errno $error\n";
438 if ( !$wgCommandLineMode ) {
439 $message = nl2br( $message );
440 }
441 wfDebugDieBacktrace( $message );
442 } else {
443 // this calls wfAbruptExit()
444 $this->mOut->databaseError( $fname, $sql, $error, $errno );
445 }
446 }
447 $this->ignoreErrors( $ignore );
448 }
449
450
451 /**
452 * Intended to be compatible with the PEAR::DB wrapper functions.
453 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
454 *
455 * ? = scalar value, quoted as necessary
456 * ! = raw SQL bit (a function for instance)
457 * & = filename; reads the file and inserts as a blob
458 * (we don't use this though...)
459 */
460 function prepare( $sql, $func = 'Database::prepare' ) {
461 /* MySQL doesn't support prepared statements (yet), so just
462 pack up the query for reference. We'll manually replace
463 the bits later. */
464 return array( 'query' => $sql, 'func' => $func );
465 }
466
467 function freePrepared( $prepared ) {
468 /* No-op for MySQL */
469 }
470
471 /**
472 * Execute a prepared query with the various arguments
473 * @param string $prepared the prepared sql
474 * @param mixed $args Either an array here, or put scalars as varargs
475 */
476 function execute( $prepared, $args = null ) {
477 if( !is_array( $args ) ) {
478 # Pull the var args
479 $args = func_get_args();
480 array_shift( $args );
481 }
482 $sql = $this->fillPrepared( $prepared['query'], $args );
483 return $this->query( $sql, $prepared['func'] );
484 }
485
486 /**
487 * Prepare & execute an SQL statement, quoting and inserting arguments
488 * in the appropriate places.
489 * @param string $query
490 * @param string $args ...
491 */
492 function safeQuery( $query, $args = null ) {
493 $prepared = $this->prepare( $query, 'Database::safeQuery' );
494 if( !is_array( $args ) ) {
495 # Pull the var args
496 $args = func_get_args();
497 array_shift( $args );
498 }
499 $retval = $this->execute( $prepared, $args );
500 $this->freePrepared( $prepared );
501 return $retval;
502 }
503
504 /**
505 * For faking prepared SQL statements on DBs that don't support
506 * it directly.
507 * @param string $preparedSql - a 'preparable' SQL statement
508 * @param array $args - array of arguments to fill it with
509 * @return string executable SQL
510 */
511 function fillPrepared( $preparedQuery, $args ) {
512 $n = 0;
513 reset( $args );
514 $this->preparedArgs =& $args;
515 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
516 array( &$this, 'fillPreparedArg' ), $preparedQuery );
517 }
518
519 /**
520 * preg_callback func for fillPrepared()
521 * The arguments should be in $this->preparedArgs and must not be touched
522 * while we're doing this.
523 *
524 * @param array $matches
525 * @return string
526 * @access private
527 */
528 function fillPreparedArg( $matches ) {
529 switch( $matches[1] ) {
530 case '\\?': return '?';
531 case '\\!': return '!';
532 case '\\&': return '&';
533 }
534 list( $n, $arg ) = each( $this->preparedArgs );
535 switch( $matches[1] ) {
536 case '?': return $this->addQuotes( $arg );
537 case '!': return $arg;
538 case '&':
539 # return $this->addQuotes( file_get_contents( $arg ) );
540 wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
541 default:
542 wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
543 }
544 }
545
546 /**#@+
547 * @param mixed $res A SQL result
548 */
549 /**
550 * Free a result object
551 */
552 function freeResult( $res ) {
553 if ( !@/**/mysql_free_result( $res ) ) {
554 wfDebugDieBacktrace( "Unable to free MySQL result\n" );
555 }
556 }
557
558 /**
559 * Fetch the next row from the given result object, in object form
560 */
561 function fetchObject( $res ) {
562 @/**/$row = mysql_fetch_object( $res );
563 if( mysql_errno() ) {
564 wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
565 }
566 return $row;
567 }
568
569 /**
570 * Fetch the next row from the given result object
571 * Returns an array
572 */
573 function fetchRow( $res ) {
574 @/**/$row = mysql_fetch_array( $res );
575 if (mysql_errno() ) {
576 wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
577 }
578 return $row;
579 }
580
581 /**
582 * Get the number of rows in a result object
583 */
584 function numRows( $res ) {
585 @/**/$n = mysql_num_rows( $res );
586 if( mysql_errno() ) {
587 wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
588 }
589 return $n;
590 }
591
592 /**
593 * Get the number of fields in a result object
594 * See documentation for mysql_num_fields()
595 */
596 function numFields( $res ) { return mysql_num_fields( $res ); }
597
598 /**
599 * Get a field name in a result object
600 * See documentation for mysql_field_name()
601 */
602 function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
603
604 /**
605 * Get the inserted value of an auto-increment row
606 *
607 * The value inserted should be fetched from nextSequenceValue()
608 *
609 * Example:
610 * $id = $dbw->nextSequenceValue('page_page_id_seq');
611 * $dbw->insert('page',array('page_id' => $id));
612 * $id = $dbw->insertId();
613 */
614 function insertId() { return mysql_insert_id( $this->mConn ); }
615
616 /**
617 * Change the position of the cursor in a result object
618 * See mysql_data_seek()
619 */
620 function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
621
622 /**
623 * Get the last error number
624 * See mysql_errno()
625 */
626 function lastErrno() {
627 if ( $this->mConn ) {
628 return mysql_errno( $this->mConn );
629 } else {
630 return mysql_errno();
631 }
632 }
633
634 /**
635 * Get a description of the last error
636 * See mysql_error() for more details
637 */
638 function lastError() {
639 if ( $this->mConn ) {
640 # Even if it's non-zero, it can still be invalid
641 wfSuppressWarnings();
642 $error = mysql_error( $this->mConn );
643 if ( !$error ) {
644 $error = mysql_error();
645 }
646 wfRestoreWarnings();
647 } else {
648 $error = mysql_error();
649 }
650 if( $error ) {
651 $error .= ' (' . $this->mServer . ')';
652 }
653 return $error;
654 }
655 /**
656 * Get the number of rows affected by the last write query
657 * See mysql_affected_rows() for more details
658 */
659 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
660 /**#@-*/ // end of template : @param $result
661
662 /**
663 * Simple UPDATE wrapper
664 * Usually aborts on failure
665 * If errors are explicitly ignored, returns success
666 *
667 * This function exists for historical reasons, Database::update() has a more standard
668 * calling convention and feature set
669 */
670 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
671 {
672 $table = $this->tableName( $table );
673 $sql = "UPDATE $table SET $var = '" .
674 $this->strencode( $value ) . "' WHERE ($cond)";
675 return (bool)$this->query( $sql, DB_MASTER, $fname );
676 }
677
678 /**
679 * Simple SELECT wrapper, returns a single field, input must be encoded
680 * Usually aborts on failure
681 * If errors are explicitly ignored, returns FALSE on failure
682 */
683 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
684 if ( !is_array( $options ) ) {
685 $options = array( $options );
686 }
687 $options['LIMIT'] = 1;
688
689 $res = $this->select( $table, $var, $cond, $fname, $options );
690 if ( $res === false || !$this->numRows( $res ) ) {
691 return false;
692 }
693 $row = $this->fetchRow( $res );
694 if ( $row !== false ) {
695 $this->freeResult( $res );
696 return $row[0];
697 } else {
698 return false;
699 }
700 }
701
702 /**
703 * Returns an optional USE INDEX clause to go after the table, and a
704 * string to go at the end of the query
705 *
706 * @access private
707 *
708 * @param array $options an associative array of options to be turned into
709 * an SQL query, valid keys are listed in the function.
710 * @return array
711 */
712 function makeSelectOptions( $options ) {
713 $tailOpts = '';
714
715 if ( isset( $options['GROUP BY'] ) ) {
716 $tailOpts .= " GROUP BY {$options['GROUP BY']}";
717 }
718 if ( isset( $options['ORDER BY'] ) ) {
719 $tailOpts .= " ORDER BY {$options['ORDER BY']}";
720 }
721 if (isset($options['LIMIT'])) {
722 $tailOpts .= $this->limitResult('', $options['LIMIT'],
723 isset($options['OFFSET']) ? $options['OFFSET'] : false);
724 }
725 if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
726 $tailOpts .= ' FOR UPDATE';
727 }
728
729 if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
730 $tailOpts .= ' LOCK IN SHARE MODE';
731 }
732
733 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
734 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
735 } else {
736 $useIndex = '';
737 }
738 return array( $useIndex, $tailOpts );
739 }
740
741 /**
742 * SELECT wrapper
743 */
744 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
745 {
746 if( is_array( $vars ) ) {
747 $vars = implode( ',', $vars );
748 }
749 if( !is_array( $options ) ) {
750 $options = array( $options );
751 }
752 if( is_array( $table ) ) {
753 if ( @is_array( $options['USE INDEX'] ) )
754 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
755 else
756 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
757 } elseif ($table!='') {
758 $from = ' FROM ' . $this->tableName( $table );
759 } else {
760 $from = '';
761 }
762
763 list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
764
765 if( !empty( $conds ) ) {
766 if ( is_array( $conds ) ) {
767 $conds = $this->makeList( $conds, LIST_AND );
768 }
769 $sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
770 } else {
771 $sql = "SELECT $vars $from $useIndex $tailOpts";
772 }
773
774 return $this->query( $sql, $fname );
775 }
776
777 /**
778 * Single row SELECT wrapper
779 * Aborts or returns FALSE on error
780 *
781 * $vars: the selected variables
782 * $conds: a condition map, terms are ANDed together.
783 * Items with numeric keys are taken to be literal conditions
784 * Takes an array of selected variables, and a condition map, which is ANDed
785 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
786 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
787 * $obj- >page_id is the ID of the Astronomy article
788 *
789 * @todo migrate documentation to phpdocumentor format
790 */
791 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
792 $options['LIMIT'] = 1;
793 $res = $this->select( $table, $vars, $conds, $fname, $options );
794 if ( $res === false )
795 return false;
796 if ( !$this->numRows($res) ) {
797 $this->freeResult($res);
798 return false;
799 }
800 $obj = $this->fetchObject( $res );
801 $this->freeResult( $res );
802 return $obj;
803
804 }
805
806 /**
807 * Removes most variables from an SQL query and replaces them with X or N for numbers.
808 * It's only slightly flawed. Don't use for anything important.
809 *
810 * @param string $sql A SQL Query
811 * @static
812 */
813 function generalizeSQL( $sql ) {
814 # This does the same as the regexp below would do, but in such a way
815 # as to avoid crashing php on some large strings.
816 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
817
818 $sql = str_replace ( "\\\\", '', $sql);
819 $sql = str_replace ( "\\'", '', $sql);
820 $sql = str_replace ( "\\\"", '', $sql);
821 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
822 $sql = preg_replace ('/".*"/s', "'X'", $sql);
823
824 # All newlines, tabs, etc replaced by single space
825 $sql = preg_replace ( "/\s+/", ' ', $sql);
826
827 # All numbers => N
828 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
829
830 return $sql;
831 }
832
833 /**
834 * Determines whether a field exists in a table
835 * Usually aborts on failure
836 * If errors are explicitly ignored, returns NULL on failure
837 */
838 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
839 $table = $this->tableName( $table );
840 $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
841 if ( !$res ) {
842 return NULL;
843 }
844
845 $found = false;
846
847 while ( $row = $this->fetchObject( $res ) ) {
848 if ( $row->Field == $field ) {
849 $found = true;
850 break;
851 }
852 }
853 return $found;
854 }
855
856 /**
857 * Determines whether an index exists
858 * Usually aborts on failure
859 * If errors are explicitly ignored, returns NULL on failure
860 */
861 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
862 $info = $this->indexInfo( $table, $index, $fname );
863 if ( is_null( $info ) ) {
864 return NULL;
865 } else {
866 return $info !== false;
867 }
868 }
869
870
871 /**
872 * Get information about an index into an object
873 * Returns false if the index does not exist
874 */
875 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
876 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
877 # SHOW INDEX should work for 3.x and up:
878 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
879 $table = $this->tableName( $table );
880 $sql = 'SHOW INDEX FROM '.$table;
881 $res = $this->query( $sql, $fname );
882 if ( !$res ) {
883 return NULL;
884 }
885
886 while ( $row = $this->fetchObject( $res ) ) {
887 if ( $row->Key_name == $index ) {
888 return $row;
889 }
890 }
891 return false;
892 }
893
894 /**
895 * Query whether a given table exists
896 */
897 function tableExists( $table ) {
898 $table = $this->tableName( $table );
899 $old = $this->ignoreErrors( true );
900 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
901 $this->ignoreErrors( $old );
902 if( $res ) {
903 $this->freeResult( $res );
904 return true;
905 } else {
906 return false;
907 }
908 }
909
910 /**
911 * mysql_fetch_field() wrapper
912 * Returns false if the field doesn't exist
913 *
914 * @param $table
915 * @param $field
916 */
917 function fieldInfo( $table, $field ) {
918 $table = $this->tableName( $table );
919 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
920 $n = mysql_num_fields( $res );
921 for( $i = 0; $i < $n; $i++ ) {
922 $meta = mysql_fetch_field( $res, $i );
923 if( $field == $meta->name ) {
924 return $meta;
925 }
926 }
927 return false;
928 }
929
930 /**
931 * mysql_field_type() wrapper
932 */
933 function fieldType( $res, $index ) {
934 return mysql_field_type( $res, $index );
935 }
936
937 /**
938 * Determines if a given index is unique
939 */
940 function indexUnique( $table, $index ) {
941 $indexInfo = $this->indexInfo( $table, $index );
942 if ( !$indexInfo ) {
943 return NULL;
944 }
945 return !$indexInfo->Non_unique;
946 }
947
948 /**
949 * INSERT wrapper, inserts an array into a table
950 *
951 * $a may be a single associative array, or an array of these with numeric keys, for
952 * multi-row insert.
953 *
954 * Usually aborts on failure
955 * If errors are explicitly ignored, returns success
956 */
957 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
958 # No rows to insert, easy just return now
959 if ( !count( $a ) ) {
960 return true;
961 }
962
963 $table = $this->tableName( $table );
964 if ( !is_array( $options ) ) {
965 $options = array( $options );
966 }
967 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
968 $multi = true;
969 $keys = array_keys( $a[0] );
970 } else {
971 $multi = false;
972 $keys = array_keys( $a );
973 }
974
975 $sql = 'INSERT ' . implode( ' ', $options ) .
976 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
977
978 if ( $multi ) {
979 $first = true;
980 foreach ( $a as $row ) {
981 if ( $first ) {
982 $first = false;
983 } else {
984 $sql .= ',';
985 }
986 $sql .= '(' . $this->makeList( $row ) . ')';
987 }
988 } else {
989 $sql .= '(' . $this->makeList( $a ) . ')';
990 }
991 return (bool)$this->query( $sql, $fname );
992 }
993
994 /**
995 * Make UPDATE options for the Database::update function
996 *
997 * @access private
998 * @param array $options The options passed to Database::update
999 * @return string
1000 */
1001 function makeUpdateOptions( $options ) {
1002 if( !is_array( $options ) ) {
1003 $options = array( $options );
1004 }
1005 $opts = array();
1006 if ( in_array( 'LOW_PRIORITY', $options ) )
1007 $opts[] = $this->lowPriorityOption();
1008 if ( in_array( 'IGNORE', $options ) )
1009 $opts[] = 'IGNORE';
1010 return implode(' ', $opts);
1011 }
1012
1013 /**
1014 * UPDATE wrapper, takes a condition array and a SET array
1015 *
1016 * @param string $table The table to UPDATE
1017 * @param array $values An array of values to SET
1018 * @param array $conds An array of conditions (WHERE)
1019 * @param string $fname The Class::Function calling this function
1020 * (for the log)
1021 * @param array $options An array of UPDATE options, can be one or
1022 * more of IGNORE, LOW_PRIORITY
1023 */
1024 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1025 $table = $this->tableName( $table );
1026 $opts = $this->makeUpdateOptions( $options );
1027 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1028 if ( $conds != '*' ) {
1029 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1030 }
1031 $this->query( $sql, $fname );
1032 }
1033
1034 /**
1035 * Makes a wfStrencoded list from an array
1036 * $mode: LIST_COMMA - comma separated, no field names
1037 * LIST_AND - ANDed WHERE clause (without the WHERE)
1038 * LIST_SET - comma separated with field names, like a SET clause
1039 * LIST_NAMES - comma separated field names
1040 */
1041 function makeList( $a, $mode = LIST_COMMA ) {
1042 if ( !is_array( $a ) ) {
1043 wfDebugDieBacktrace( 'Database::makeList called with incorrect parameters' );
1044 }
1045
1046 $first = true;
1047 $list = '';
1048 foreach ( $a as $field => $value ) {
1049 if ( !$first ) {
1050 if ( $mode == LIST_AND ) {
1051 $list .= ' AND ';
1052 } elseif($mode == LIST_OR) {
1053 $list .= ' OR ';
1054 } else {
1055 $list .= ',';
1056 }
1057 } else {
1058 $first = false;
1059 }
1060 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1061 $list .= "($value)";
1062 } elseif ( $mode == LIST_AND && is_array ($value) ) {
1063 $list .= $field." IN (".$this->makeList($value).") ";
1064 } else {
1065 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1066 $list .= "$field = ";
1067 }
1068 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1069 }
1070 }
1071 return $list;
1072 }
1073
1074 /**
1075 * Change the current database
1076 */
1077 function selectDB( $db ) {
1078 $this->mDBname = $db;
1079 return mysql_select_db( $db, $this->mConn );
1080 }
1081
1082 /**
1083 * Starts a timer which will kill the DB thread after $timeout seconds
1084 */
1085 function startTimer( $timeout ) {
1086 global $IP;
1087 if( function_exists( 'mysql_thread_id' ) ) {
1088 # This will kill the query if it's still running after $timeout seconds.
1089 $tid = mysql_thread_id( $this->mConn );
1090 exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
1091 }
1092 }
1093
1094 /**
1095 * Stop a timer started by startTimer()
1096 * Currently unimplemented.
1097 *
1098 */
1099 function stopTimer() { }
1100
1101 /**
1102 * Format a table name ready for use in constructing an SQL query
1103 *
1104 * This does two important things: it quotes table names which as necessary,
1105 * and it adds a table prefix if there is one.
1106 *
1107 * All functions of this object which require a table name call this function
1108 * themselves. Pass the canonical name to such functions. This is only needed
1109 * when calling query() directly.
1110 *
1111 * @param string $name database table name
1112 */
1113 function tableName( $name ) {
1114 global $wgSharedDB;
1115 # Skip quoted literals
1116 if ( $name{0} != '`' ) {
1117 if ( $this->mTablePrefix !== '' && strpos( '.', $name ) === false ) {
1118 $name = "{$this->mTablePrefix}$name";
1119 }
1120 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1121 $name = "`$wgSharedDB`.`$name`";
1122 } else {
1123 # Standard quoting
1124 $name = "`$name`";
1125 }
1126 }
1127 return $name;
1128 }
1129
1130 /**
1131 * Fetch a number of table names into an array
1132 * This is handy when you need to construct SQL for joins
1133 *
1134 * Example:
1135 * extract($dbr->tableNames('user','watchlist'));
1136 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1137 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1138 */
1139 function tableNames() {
1140 $inArray = func_get_args();
1141 $retVal = array();
1142 foreach ( $inArray as $name ) {
1143 $retVal[$name] = $this->tableName( $name );
1144 }
1145 return $retVal;
1146 }
1147
1148 /**
1149 * @access private
1150 */
1151 function tableNamesWithUseIndex( $tables, $use_index ) {
1152 $ret = array();
1153
1154 foreach ( $tables as $table )
1155 if ( @$use_index[$table] !== null )
1156 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1157 else
1158 $ret[] = $this->tableName( $table );
1159
1160 return implode( ',', $ret );
1161 }
1162
1163 /**
1164 * Wrapper for addslashes()
1165 * @param string $s String to be slashed.
1166 * @return string slashed string.
1167 */
1168 function strencode( $s ) {
1169 return addslashes( $s );
1170 }
1171
1172 /**
1173 * If it's a string, adds quotes and backslashes
1174 * Otherwise returns as-is
1175 */
1176 function addQuotes( $s ) {
1177 if ( is_null( $s ) ) {
1178 return 'NULL';
1179 } else {
1180 # This will also quote numeric values. This should be harmless,
1181 # and protects against weird problems that occur when they really
1182 # _are_ strings such as article titles and string->number->string
1183 # conversion is not 1:1.
1184 return "'" . $this->strencode( $s ) . "'";
1185 }
1186 }
1187
1188 /**
1189 * Escape string for safe LIKE usage
1190 */
1191 function escapeLike( $s ) {
1192 $s=$this->strencode( $s );
1193 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1194 return $s;
1195 }
1196
1197 /**
1198 * Returns an appropriately quoted sequence value for inserting a new row.
1199 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1200 * subclass will return an integer, and save the value for insertId()
1201 */
1202 function nextSequenceValue( $seqName ) {
1203 return NULL;
1204 }
1205
1206 /**
1207 * USE INDEX clause
1208 * PostgreSQL doesn't have them and returns ""
1209 */
1210 function useIndexClause( $index ) {
1211 return "FORCE INDEX ($index)";
1212 }
1213
1214 /**
1215 * REPLACE query wrapper
1216 * PostgreSQL simulates this with a DELETE followed by INSERT
1217 * $row is the row to insert, an associative array
1218 * $uniqueIndexes is an array of indexes. Each element may be either a
1219 * field name or an array of field names
1220 *
1221 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1222 * However if you do this, you run the risk of encountering errors which wouldn't have
1223 * occurred in MySQL
1224 *
1225 * @todo migrate comment to phodocumentor format
1226 */
1227 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1228 $table = $this->tableName( $table );
1229
1230 # Single row case
1231 if ( !is_array( reset( $rows ) ) ) {
1232 $rows = array( $rows );
1233 }
1234
1235 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1236 $first = true;
1237 foreach ( $rows as $row ) {
1238 if ( $first ) {
1239 $first = false;
1240 } else {
1241 $sql .= ',';
1242 }
1243 $sql .= '(' . $this->makeList( $row ) . ')';
1244 }
1245 return $this->query( $sql, $fname );
1246 }
1247
1248 /**
1249 * DELETE where the condition is a join
1250 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1251 *
1252 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1253 * join condition matches, set $conds='*'
1254 *
1255 * DO NOT put the join condition in $conds
1256 *
1257 * @param string $delTable The table to delete from.
1258 * @param string $joinTable The other table.
1259 * @param string $delVar The variable to join on, in the first table.
1260 * @param string $joinVar The variable to join on, in the second table.
1261 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1262 */
1263 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1264 if ( !$conds ) {
1265 wfDebugDieBacktrace( 'Database::deleteJoin() called with empty $conds' );
1266 }
1267
1268 $delTable = $this->tableName( $delTable );
1269 $joinTable = $this->tableName( $joinTable );
1270 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1271 if ( $conds != '*' ) {
1272 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1273 }
1274
1275 return $this->query( $sql, $fname );
1276 }
1277
1278 /**
1279 * Returns the size of a text field, or -1 for "unlimited"
1280 */
1281 function textFieldSize( $table, $field ) {
1282 $table = $this->tableName( $table );
1283 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1284 $res = $this->query( $sql, 'Database::textFieldSize' );
1285 $row = $this->fetchObject( $res );
1286 $this->freeResult( $res );
1287
1288 if ( preg_match( "/\((.*)\)/", $row->Type, $m ) ) {
1289 $size = $m[1];
1290 } else {
1291 $size = -1;
1292 }
1293 return $size;
1294 }
1295
1296 /**
1297 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1298 */
1299 function lowPriorityOption() {
1300 return 'LOW_PRIORITY';
1301 }
1302
1303 /**
1304 * DELETE query wrapper
1305 *
1306 * Use $conds == "*" to delete all rows
1307 */
1308 function delete( $table, $conds, $fname = 'Database::delete' ) {
1309 if ( !$conds ) {
1310 wfDebugDieBacktrace( 'Database::delete() called with no conditions' );
1311 }
1312 $table = $this->tableName( $table );
1313 $sql = "DELETE FROM $table";
1314 if ( $conds != '*' ) {
1315 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1316 }
1317 return $this->query( $sql, $fname );
1318 }
1319
1320 /**
1321 * INSERT SELECT wrapper
1322 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1323 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1324 * $conds may be "*" to copy the whole table
1325 * srcTable may be an array of tables.
1326 */
1327 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
1328 $destTable = $this->tableName( $destTable );
1329 if( is_array( $srcTable ) ) {
1330 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1331 } else {
1332 $srcTable = $this->tableName( $srcTable );
1333 }
1334 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1335 ' SELECT ' . implode( ',', $varMap ) .
1336 " FROM $srcTable";
1337 if ( $conds != '*' ) {
1338 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1339 }
1340 return $this->query( $sql, $fname );
1341 }
1342
1343 /**
1344 * Construct a LIMIT query with optional offset
1345 * This is used for query pages
1346 * $sql string SQL query we will append the limit too
1347 * $limit integer the SQL limit
1348 * $offset integer the SQL offset (default false)
1349 */
1350 function limitResult($sql, $limit, $offset=false) {
1351 return " $sql LIMIT ".((is_numeric($offset) && $offset != 0)?"{$offset},":"")."{$limit} ";
1352 }
1353 function limitResultForUpdate($sql, $num) {
1354 return $this->limitResult($sql, $num, 0);
1355 }
1356
1357 /**
1358 * Returns an SQL expression for a simple conditional.
1359 * Uses IF on MySQL.
1360 *
1361 * @param string $cond SQL expression which will result in a boolean value
1362 * @param string $trueVal SQL expression to return if true
1363 * @param string $falseVal SQL expression to return if false
1364 * @return string SQL fragment
1365 */
1366 function conditional( $cond, $trueVal, $falseVal ) {
1367 return " IF($cond, $trueVal, $falseVal) ";
1368 }
1369
1370 /**
1371 * Determines if the last failure was due to a deadlock
1372 */
1373 function wasDeadlock() {
1374 return $this->lastErrno() == 1213;
1375 }
1376
1377 /**
1378 * Perform a deadlock-prone transaction.
1379 *
1380 * This function invokes a callback function to perform a set of write
1381 * queries. If a deadlock occurs during the processing, the transaction
1382 * will be rolled back and the callback function will be called again.
1383 *
1384 * Usage:
1385 * $dbw->deadlockLoop( callback, ... );
1386 *
1387 * Extra arguments are passed through to the specified callback function.
1388 *
1389 * Returns whatever the callback function returned on its successful,
1390 * iteration, or false on error, for example if the retry limit was
1391 * reached.
1392 */
1393 function deadlockLoop() {
1394 $myFname = 'Database::deadlockLoop';
1395
1396 $this->begin();
1397 $args = func_get_args();
1398 $function = array_shift( $args );
1399 $oldIgnore = $this->ignoreErrors( true );
1400 $tries = DEADLOCK_TRIES;
1401 if ( is_array( $function ) ) {
1402 $fname = $function[0];
1403 } else {
1404 $fname = $function;
1405 }
1406 do {
1407 $retVal = call_user_func_array( $function, $args );
1408 $error = $this->lastError();
1409 $errno = $this->lastErrno();
1410 $sql = $this->lastQuery();
1411
1412 if ( $errno ) {
1413 if ( $this->wasDeadlock() ) {
1414 # Retry
1415 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1416 } else {
1417 $this->reportQueryError( $error, $errno, $sql, $fname );
1418 }
1419 }
1420 } while( $this->wasDeadlock() && --$tries > 0 );
1421 $this->ignoreErrors( $oldIgnore );
1422 if ( $tries <= 0 ) {
1423 $this->query( 'ROLLBACK', $myFname );
1424 $this->reportQueryError( $error, $errno, $sql, $fname );
1425 return false;
1426 } else {
1427 $this->query( 'COMMIT', $myFname );
1428 return $retVal;
1429 }
1430 }
1431
1432 /**
1433 * Do a SELECT MASTER_POS_WAIT()
1434 *
1435 * @param string $file the binlog file
1436 * @param string $pos the binlog position
1437 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1438 */
1439 function masterPosWait( $file, $pos, $timeout ) {
1440 $fname = 'Database::masterPosWait';
1441 wfProfileIn( $fname );
1442
1443
1444 # Commit any open transactions
1445 $this->immediateCommit();
1446
1447 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1448 $encFile = $this->strencode( $file );
1449 $sql = "SELECT MASTER_POS_WAIT('$encFile', $pos, $timeout)";
1450 $res = $this->doQuery( $sql );
1451 if ( $res && $row = $this->fetchRow( $res ) ) {
1452 $this->freeResult( $res );
1453 wfProfileOut( $fname );
1454 return $row[0];
1455 } else {
1456 wfProfileOut( $fname );
1457 return false;
1458 }
1459 }
1460
1461 /**
1462 * Get the position of the master from SHOW SLAVE STATUS
1463 */
1464 function getSlavePos() {
1465 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1466 $row = $this->fetchObject( $res );
1467 if ( $row ) {
1468 return array( $row->Master_Log_File, $row->Read_Master_Log_Pos );
1469 } else {
1470 return array( false, false );
1471 }
1472 }
1473
1474 /**
1475 * Get the position of the master from SHOW MASTER STATUS
1476 */
1477 function getMasterPos() {
1478 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1479 $row = $this->fetchObject( $res );
1480 if ( $row ) {
1481 return array( $row->File, $row->Position );
1482 } else {
1483 return array( false, false );
1484 }
1485 }
1486
1487 /**
1488 * Begin a transaction, or if a transaction has already started, continue it
1489 */
1490 function begin( $fname = 'Database::begin' ) {
1491 if ( !$this->mTrxLevel ) {
1492 $this->immediateBegin( $fname );
1493 } else {
1494 $this->mTrxLevel++;
1495 }
1496 }
1497
1498 /**
1499 * End a transaction, or decrement the nest level if transactions are nested
1500 */
1501 function commit( $fname = 'Database::commit' ) {
1502 if ( $this->mTrxLevel ) {
1503 $this->mTrxLevel--;
1504 }
1505 if ( !$this->mTrxLevel ) {
1506 $this->immediateCommit( $fname );
1507 }
1508 }
1509
1510 /**
1511 * Rollback a transaction
1512 */
1513 function rollback( $fname = 'Database::rollback' ) {
1514 $this->query( 'ROLLBACK', $fname );
1515 $this->mTrxLevel = 0;
1516 }
1517
1518 /**
1519 * Begin a transaction, committing any previously open transaction
1520 */
1521 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1522 $this->query( 'BEGIN', $fname );
1523 $this->mTrxLevel = 1;
1524 }
1525
1526 /**
1527 * Commit transaction, if one is open
1528 */
1529 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1530 $this->query( 'COMMIT', $fname );
1531 $this->mTrxLevel = 0;
1532 }
1533
1534 /**
1535 * Return MW-style timestamp used for MySQL schema
1536 */
1537 function timestamp( $ts=0 ) {
1538 return wfTimestamp(TS_MW,$ts);
1539 }
1540
1541 /**
1542 * Local database timestamp format or null
1543 */
1544 function timestampOrNull( $ts = null ) {
1545 if( is_null( $ts ) ) {
1546 return null;
1547 } else {
1548 return $this->timestamp( $ts );
1549 }
1550 }
1551
1552 /**
1553 * @todo document
1554 */
1555 function resultObject( $result ) {
1556 if( empty( $result ) ) {
1557 return NULL;
1558 } else {
1559 return new ResultWrapper( $this, $result );
1560 }
1561 }
1562
1563 /**
1564 * Return aggregated value alias
1565 */
1566 function aggregateValue ($valuedata,$valuename='value') {
1567 return $valuename;
1568 }
1569
1570 /**
1571 * @return string wikitext of a link to the server software's web site
1572 */
1573 function getSoftwareLink() {
1574 return "[http://www.mysql.com/ MySQL]";
1575 }
1576
1577 /**
1578 * @return string Version information from the database
1579 */
1580 function getServerVersion() {
1581 return mysql_get_server_info();
1582 }
1583
1584 /**
1585 * Ping the server and try to reconnect if it there is no connection
1586 */
1587 function ping() {
1588 if( function_exists( 'mysql_ping' ) ) {
1589 return mysql_ping( $this->mConn );
1590 } else {
1591 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1592 return true;
1593 }
1594 }
1595
1596 /**
1597 * Get slave lag.
1598 * At the moment, this will only work if the DB user has the PROCESS privilege
1599 */
1600 function getLag() {
1601 $res = $this->query( 'SHOW PROCESSLIST' );
1602 # Find slave SQL thread. Assumed to be the second one running, which is a bit
1603 # dubious, but unfortunately there's no easy rigorous way
1604 $slaveThreads = 0;
1605 while ( $row = $this->fetchObject( $res ) ) {
1606 if ( $row->User == 'system user' ) {
1607 if ( ++$slaveThreads == 2 ) {
1608 # This is it, return the time
1609 return $row->Time;
1610 }
1611 }
1612 }
1613 return false;
1614 }
1615
1616 /**
1617 * Get status information from SHOW STATUS in an associative array
1618 */
1619 function getStatus() {
1620 $res = $this->query( 'SHOW STATUS' );
1621 $status = array();
1622 while ( $row = $this->fetchObject( $res ) ) {
1623 $status[$row->Variable_name] = $row->Value;
1624 }
1625 return $status;
1626 }
1627
1628 /**
1629 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1630 */
1631 function maxListLen() {
1632 return 0;
1633 }
1634
1635 function encodeBlob($b) {
1636 return $b;
1637 }
1638
1639 function notNullTimestamp() {
1640 return "!= 0";
1641 }
1642 function isNullTimestamp() {
1643 return "= '0'";
1644 }
1645 }
1646
1647 /**
1648 * Database abstraction object for mySQL
1649 * Inherit all methods and properties of Database::Database()
1650 *
1651 * @package MediaWiki
1652 * @see Database
1653 */
1654 class DatabaseMysql extends Database {
1655 # Inherit all
1656 }
1657
1658
1659 /**
1660 * Result wrapper for grabbing data queried by someone else
1661 *
1662 * @package MediaWiki
1663 */
1664 class ResultWrapper {
1665 var $db, $result;
1666
1667 /**
1668 * @todo document
1669 */
1670 function ResultWrapper( $database, $result ) {
1671 $this->db =& $database;
1672 $this->result =& $result;
1673 }
1674
1675 /**
1676 * @todo document
1677 */
1678 function numRows() {
1679 return $this->db->numRows( $this->result );
1680 }
1681
1682 /**
1683 * @todo document
1684 */
1685 function fetchObject() {
1686 return $this->db->fetchObject( $this->result );
1687 }
1688
1689 /**
1690 * @todo document
1691 */
1692 function &fetchRow() {
1693 return $this->db->fetchRow( $this->result );
1694 }
1695
1696 /**
1697 * @todo document
1698 */
1699 function free() {
1700 $this->db->freeResult( $this->result );
1701 unset( $this->result );
1702 unset( $this->db );
1703 }
1704
1705 function seek( $row ) {
1706 $this->db->dataSeek( $this->result, $row );
1707 }
1708 }
1709
1710 #------------------------------------------------------------------------------
1711 # Global functions
1712 #------------------------------------------------------------------------------
1713
1714 /**
1715 * Standard fail function, called by default when a connection cannot be
1716 * established.
1717 * Displays the file cache if possible
1718 */
1719 function wfEmergencyAbort( &$conn, $error ) {
1720 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
1721 global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
1722
1723 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
1724 # Hard coding strings instead.
1725
1726 $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
1727 $mainpage = 'Main Page';
1728 $searchdisabled = <<<EOT
1729 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
1730 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
1731 EOT;
1732
1733 $googlesearch = "
1734 <!-- SiteSearch Google -->
1735 <FORM method=GET action=\"http://www.google.com/search\">
1736 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
1737 <A HREF=\"http://www.google.com/\">
1738 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
1739 border=\"0\" ALT=\"Google\"></A>
1740 </td>
1741 <td>
1742 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
1743 <INPUT type=submit name=btnG VALUE=\"Google Search\">
1744 <font size=-1>
1745 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
1746 <input type='hidden' name='ie' value='$2'>
1747 <input type='hidden' name='oe' value='$2'>
1748 </font>
1749 </td></tr></TABLE>
1750 </FORM>
1751 <!-- SiteSearch Google -->";
1752 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
1753
1754
1755 if( !headers_sent() ) {
1756 header( 'HTTP/1.0 500 Internal Server Error' );
1757 header( 'Content-type: text/html; charset='.$wgOutputEncoding );
1758 /* Don't cache error pages! They cause no end of trouble... */
1759 header( 'Cache-control: none' );
1760 header( 'Pragma: nocache' );
1761 }
1762
1763 # No database access
1764 if ( is_object( $wgMessageCache ) ) {
1765 $wgMessageCache->disable();
1766 }
1767
1768 $msg = wfGetSiteNotice();
1769 if($msg == '') {
1770 $msg = str_replace( '$1', $error, $noconnect );
1771 }
1772 $text = $msg;
1773
1774 if($wgUseFileCache) {
1775 if($wgTitle) {
1776 $t =& $wgTitle;
1777 } else {
1778 if($title) {
1779 $t = Title::newFromURL( $title );
1780 } elseif (@/**/$_REQUEST['search']) {
1781 $search = $_REQUEST['search'];
1782 echo $searchdisabled;
1783 echo str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
1784 $wgInputEncoding ), $googlesearch );
1785 wfErrorExit();
1786 } else {
1787 $t = Title::newFromText( $mainpage );
1788 }
1789 }
1790
1791 $cache = new CacheManager( $t );
1792 if( $cache->isFileCached() ) {
1793 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
1794 $cachederror . "</b></p>\n";
1795
1796 $tag = '<div id="article">';
1797 $text = str_replace(
1798 $tag,
1799 $tag . $msg,
1800 $cache->fetchPageText() );
1801 }
1802 }
1803
1804 echo $text;
1805 wfErrorExit();
1806 }
1807
1808 ?>